package com.example.asa;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/viewAlerts")
public class ViewAlertsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 权限验证：仅允许居民访问
        HttpSession session = request.getSession();
        String role = (String) session.getAttribute("role");
        if (role == null || !"resident".equals(role)) {
            request.setAttribute("error", "您没有权限查看此页面");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        List<Alert> alertList;
        try {
            AlertDAO alertDAO = new AlertDAO();
            alertList = alertDAO.getAllAlerts();
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "加载预警信息失败：" + e.getMessage());
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        request.setAttribute("alertList", alertList);
        request.getRequestDispatcher("viewAlerts.jsp").forward(request, response);
    }
}
